﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HTB.DevFx.Core;
using HTB.DevFx.Utils;
using Maple.Weixin.MP.Config;
using Maple.Weixin.MP.Entities.CustomerService;
using Maple.Weixin.MP.Entities.JsonResult;
using Maple.Weixin.MP.Exceptions;
using Maple.Weixin.MP.Helpers;
using Newtonsoft.Json;
using Maple.Weixin.MP.Entities;

namespace Maple.Weixin.MP
{
    class DkfService : ServiceBase<IDkfServiceSetting>, IDkfService
    {
        private const string ErrorCode = "errcode";
        private IWeixinService weixin;
        
        protected override void OnInit() {
            weixin = ObjectService.GetObject<IWeixinService>();
        }

        #region Implementation of IDkfService

        /// <summary>
        /// 获取所有的客服信息。
        /// </summary>
        /// <returns>客服的数组。</returns>
        public DkfAccount[] GetAccounts() {
            var accessToken = weixin.GetAccessToken();
            return GetAccounts(accessToken);
        }

        /// <summary>
        /// 获取所有的客服信息。
        /// </summary>
        /// <param name="accessToken">给定的AccessToken。</param>
        /// <returns>客服的数组。</returns>
        public DkfAccount[] GetAccounts(string accessToken)
        {
            var requestUrl = WeixinHelper.GetDkfListUrl(accessToken);
            var result = HttpHelper.Get(requestUrl);
            if (result.Contains(ErrorCode))
            {
                var weixinServiceResult = JsonHelper.FromJson<WeixinServiceResult>(result, true);
                throw new WeixinRequestException(weixinServiceResult);
            }

            return JsonHelper.FromJson<DkfAccountResult>(result, true).kf_list;
        }

        /// <summary>
        /// 获取指定客服信息
        /// </summary>
        /// <param name="accountName">账号名称，格式为账号前缀@公众号微信号。</param>
        /// <returns></returns>
        public DkfAccount GetAccount(string accountName)
        {
            var dkfaccounts = GetAccounts();
            return dkfaccounts.SingleOrDefault(p=>  p.kf_account == accountName);
        }

        /// <summary>
        /// 获取指定客服信息
        /// </summary>
        /// <param name="accessToken">给定的AccessToken。</param>
        /// <param name="accountName">账号名称，格式为账号前缀@公众号微信号。</param>
        /// <returns></returns>
        public DkfAccount GetAccount(string accessToken, string accountName)
        {
            var dkfaccounts = GetAccounts(accessToken);
            return dkfaccounts.SingleOrDefault(p => p.kf_account == accountName);
        }

        /// <summary>
        /// 获取所有当前可用客服信息。
        /// </summary>
        /// <returns>当前可用的客服数组。</returns>
        public DkfOnline[] GetOnlineAccount() {
            var accessToken = weixin.GetAccessToken();
            return GetOnlineAccount(accessToken);
        }

        /// <summary>
        /// 获取所有当前可用客服信息。
        /// </summary>
        /// <param name="accessToken">给定的AccessToken。</param>
        /// <returns>当前可用的客服数组。</returns>
        public DkfOnline[] GetOnlineAccount(string accessToken)
        {
            var requestUrl = WeixinHelper.GetDkfOnlineListUrl(accessToken);
            var result = HttpHelper.Get(requestUrl);
            if (result.Contains(ErrorCode))
            {
                var weixinServiceResult = JsonHelper.FromJson<WeixinServiceResult>(result, true);
                throw new WeixinRequestException(weixinServiceResult);
            }

            return JsonHelper.FromJson<DkfOnlineResult>(result, true).kf_online_list;
        }

        /// <summary>
        /// 向系统添加多客服账号。
        /// </summary>
        /// <param name="accessToken">给定的AccessToken。</param>
        /// <param name="accountName">账号名称，格式为账号前缀@公众号微信号。</param>
        /// <param name="nickName">昵称。</param>
        /// <param name="password">密码。格式为密码明文的32位加密MD5。</param>
        /// <param name="isReturnAccount">是否返回添加后的客服信息</param>
        /// <returns>本次添加操作的结果。</returns>
        public IAOPResult AddAccount(string accessToken, string accountName, string nickName, string password, bool isReturnAccount = false)
        {
            var requestUrl = WeixinHelper.GetDkfAddUrl(accessToken);

            var result = HttpHelper.Post(requestUrl, new DkfAccount
            {
                kf_account = accountName,
                kf_nick = nickName,
                kf_password = password
            }.ToJson());

            var weixinServiceResult = JsonHelper.FromJson<WeixinServiceResult>(result, true);

            if((int)weixinServiceResult.errcode != 0 || !isReturnAccount)  
                return AOPResult.Create((int)weixinServiceResult.errcode, weixinServiceResult.errcode.ToString(), null, null);

            return AOPResult.Create<DkfAccount>((int)weixinServiceResult.errcode, weixinServiceResult.errcode.ToString(),
                GetAccount(accountName),null,null);

        }

        /// <summary>
        /// 向系统添加多客服账号。
        /// </summary>
        /// <param name="accountName">账号名称，格式为账号前缀@公众号微信号。</param>
        /// <param name="nickName">昵称。</param>
        /// <param name="password">密码。格式为密码明文的32位加密MD5。</param>
        /// <param name="isReturnAccount">是否返回添加后的客服信息</param>
        /// <returns>本次添加操作的结果。</returns>
        public IAOPResult AddAccount(string accountName, string nickName, string password, bool isReturnAccount = false)
        {
            var accessToken = weixin.GetAccessToken();
            return AddAccount(accessToken, accountName, nickName, password, isReturnAccount);
        }

        /// <summary>
        /// 设置某个客服的信息。
        /// </summary>
        /// <param name="accessToken">给定的AccessToken。</param>
        /// <param name="accountName">账号名称，格式为账号前缀@公众号微信号。</param>
        /// <param name="nickName">昵称。</param>
        /// <param name="password">密码。格式为密码明文的32位加密MD5。</param>
        /// <param name="isReturnAccount">是否返回修改后的客服信息</param>
        /// <returns>本次设置操作的结果。</returns>
        public IAOPResult EditAccount(string accessToken,string accountName, string nickName, string password, bool isReturnAccount = false)
        {
            var requestUrl = WeixinHelper.GetDkfUpdateUrl(accessToken);

            var result = HttpHelper.Post(requestUrl, new DkfAccount
            {
                kf_account = accountName,
                kf_nick = nickName,
                kf_password = password
            }.ToJson());

            var weixinServiceResult = JsonHelper.FromJson<WeixinServiceResult>(result, true);

            if ((int)weixinServiceResult.errcode != 0 || !isReturnAccount)
                return AOPResult.Create((int)weixinServiceResult.errcode, weixinServiceResult.errcode.ToString(), null, null);

            return AOPResult.Create<DkfAccount>((int)weixinServiceResult.errcode, weixinServiceResult.errcode.ToString(),
                GetAccount(accountName), null, null);
        }

        /// <summary>
        /// 设置某个客服的信息。
        /// </summary>
        /// <param name="accountName">账号名称，格式为账号前缀@公众号微信号。</param>
        /// <param name="nickName">昵称。</param>
        /// <param name="password">密码。格式为密码明文的32位加密MD5。</param>
        /// <param name="isReturnAccount">是否返回修改后的客服信息</param>
        /// <returns>本次设置操作的结果。</returns>
        public IAOPResult EditAccount(string accountName, string nickName, string password, bool isReturnAccount = false)
        {
            var accessToken = weixin.GetAccessToken();
            return EditAccount(accessToken, accountName, nickName, password, isReturnAccount);
        }


        /// <summary>
        /// 删除某个客服的账号。
        /// </summary>
        /// <param name="accessToken">给定的AccessToken。</param>
        /// <param name="accountName">账号名称，格式为账号前缀@公众号微信号。</param>
        /// <returns>本次删除操作的结果。</returns>
        public IAOPResult DeleteAccount(string accessToken,string accountName) {
           
            var requestUrl = WeixinHelper.GetDkfDelUrl(accessToken, accountName);

            var result = HttpHelper.Get(requestUrl);
            var weixinServiceResult = JsonHelper.FromJson<WeixinServiceResult>(result, true);

            return AOPResult.Create((int)weixinServiceResult.errcode, weixinServiceResult.errcode.ToString(), null, null);

        }

        /// <summary>
        /// 删除某个客服的账号。
        /// </summary>
        /// <param name="accountName">账号名称，格式为账号前缀@公众号微信号。</param>
        /// <returns>本次删除操作的结果。</returns>
        public IAOPResult DeleteAccount(string accountName)
        {
            var accessToken = weixin.GetAccessToken();
            return DeleteAccount(accessToken,accountName);

        }

        /// <summary>
        ///  获取聊天记录
        /// </summary>
        /// <param name="accessToken">给定的AccessToken。</param>
        /// <param name="openid">普通用户的标识，对当前公众号唯一</param>
        /// <param name="starttime">查询开始时间，UNIX时间戳</param>
        /// <param name="endtime">查询结束时间，UNIX时间戳，每次查询不能跨日查询</param>
        /// <param name="pagesize">每页大小，每页最多拉取1000条</param>
        /// <param name="pageindex">查询第几页，从1开始</param>
        /// <returns></returns>
        public DkfRecord[] GetChatRecords(string accessToken,string openid, string starttime, string endtime, int pagesize, int pageindex)
        {
            var requestUrl = WeixinHelper.GetDkfRecordsUrl(accessToken, openid, starttime, endtime, pagesize, pageindex);

            var postdata = JsonHelper.ToJson(new { starttime = starttime, endtime = endtime, openid = openid, pagesize = pagesize, pageindex = pageindex }, true);
            var result = HttpHelper.Post(requestUrl, postdata);

            if (result.Contains(ErrorCode))
            {
                var weixinServiceResult = JsonHelper.FromJson<WeixinServiceResult>(result, true);
                throw new WeixinRequestException(weixinServiceResult);
            }

            return JsonHelper.FromJson<DkfRecordListResult>(result, true).recordlist;
        }

        /// <summary>
        ///  获取聊天记录
        /// </summary>
        /// <param name="openid">普通用户的标识，对当前公众号唯一</param>
        /// <param name="starttime">查询开始时间，UNIX时间戳</param>
        /// <param name="endtime">查询结束时间，UNIX时间戳，每次查询不能跨日查询</param>
        /// <param name="pagesize">每页大小，每页最多拉取1000条</param>
        /// <param name="pageindex">查询第几页，从1开始</param>
        /// <returns></returns>
        public DkfRecord[] GetChatRecords(string openid, string starttime, string endtime, int pagesize, int pageindex)
        {
            var accessToken = weixin.GetAccessToken();
            return GetChatRecords(accessToken, openid, starttime, endtime, pagesize, pageindex);
        }

        #endregion
    }
}
